
import { Toast } from "antd-mobile";
import http from "@/utils/request";
import { getTokenCache, setAccountCache, setPasswordCache, setResultIdCache, setTokenCache } from "./storage";


export const apiLogin = async (params, reqCallback) => {
    if (!params) {
        reqCallback && reqCallback(false, null);
        return;
    }

    let url = process.env.REACT_APP_API_LOGIN + "";
    const res = await http.post(url, params);
    if (!res) {
        reqCallback && reqCallback(false, null);
        return;
    }

    const resCode = parseInt(res.code);
    const resObj = res.data || {};
    const resMsg = res.msg;
    const success = (resCode === 0);

    if (!success) {
        Toast.show(resMsg);
    }

    const token = resObj.token || "";
    if (token.length === 0) {
        reqCallback && reqCallback(false, null);
        return;
    }

    const account = params.username || "";
    const password = params.password || "";
    setAccountCache(account);
    setPasswordCache(password);
    setTokenCache(token);

    reqCallback && reqCallback(success, resObj);
}

export const apiResultList = async (type, reqCallback) => {
    let token = getTokenCache();
    if (token.length === 0) {
        Toast.show("请先登录!");
        reqCallback && reqCallback(false, null);
        return;
    }

    let url = process.env.REACT_APP_API_RESULT_LIST + "";
    if (type === "processing") {
        url = process.env.REACT_APP_API_PROCESSING_LIST + "";
    }
    const res = await http.post(url, { token: token });
    if (!res) {
        reqCallback && reqCallback(false, null);
        return;
    }

    const resCode = parseInt(res.code);
    const resObj = res.data || [];
    const resMsg = res.msg;
    const success = (resCode === 0);

    if (!success) {
        Toast.show(resMsg);
    }

    reqCallback && reqCallback(success, resObj);
}

export const apiScaning = async (params, reqCallback) => {
    let token = getTokenCache();
    if (token.length === 0) {
        Toast.show("请先登录!");
        reqCallback && reqCallback(false, null);
        return;
    }

    if (!params || params.length === 0) {
        reqCallback && reqCallback(false, null);
        return;
    }

    let url = process.env.REACT_APP_API_START_SCRAPE + "";
    const res = await http.post(url, { list: params, token: token });
    if (!res) {
        reqCallback && reqCallback(false, null);
        return;
    }

    const resCode = parseInt(res.code);
    const resObj = res.data || {};
    const resMsg = res.msg;
    const success = (resCode === 0);

    if (!success) {
        Toast.show(resMsg);
    }

    const resultId = resObj.resultId || "";
    if (resultId.length === 0) {
        reqCallback && reqCallback(false, null);
        return;
    }

    setResultIdCache(resultId);

    reqCallback && reqCallback(success, resObj);
}